package com.example.demo.controller;

import com.example.demo.domain.*;
import com.example.demo.services.AccountService;
import com.example.demo.services.OrderService;
import com.example.demo.services.impl.NationalPolicyResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@Controller
@RestController
public class OrderController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private NationalPolicyResult nationalPolicyResult;

    @RequestMapping(value = "/orders/{username}", method = RequestMethod.GET)
    public NationalPolicyResult getOrderByUserName(@PathVariable String username){
        List<Order> orderList = orderService.getOrdersByUsername(username);
        NationalPolicyResult result = nationalPolicyResult.success(orderList);
        return result;
    }

    @RequestMapping(value = "/orders/{ID}",method = RequestMethod.GET)
    public NationalPolicyResult getOrderByID(@PathVariable int ID){
        Order order = orderService.getOrder(ID);
        if(order != null){
            NationalPolicyResult result = nationalPolicyResult.success(order);
            return result;
        }
        else {
            NationalPolicyResult result = nationalPolicyResult.build(2,"请求的订单不存在！",null);
            return result;
        }
    }

    @RequestMapping(value = "/orders/new",method = RequestMethod.POST)
    public NationalPolicyResult generateOrder(@RequestBody String order0) throws JsonProcessingException {
        OrderTemp orderTemp = new ObjectMapper().readValue(order0, OrderTemp.class);
        CartTemp cartTemp = orderTemp.getCart();
        Account account = accountService.getAccount(orderTemp.getLoginAccount().getUsername());
        Cart cart = new Cart();
        for (CartItem cartitem:cartTemp.getCartItem()) {
            cart.addItemAndReturnCartItem(cartitem.getItem(),true).calculateTotal();
            cart.setQuantityByItemId(cartitem.getItem().getItemId(),cartitem.getQuantity());
        }
        Order order = new Order();
        order.initOrder(account,cart);
//        orderService.insertOrder(order);
        return nationalPolicyResult.build(2,"订单添加成功！",order);
    }

    @RequestMapping(value = "/orders/", method = RequestMethod.PUT)
    public NationalPolicyResult insertOrder(@RequestBody String order) throws JsonProcessingException {
        Order order1 = new ObjectMapper().readValue(order, Order.class);
        orderService.insertOrder(order1);
        return nationalPolicyResult.build(2,"订单添加成功！",order1);
    }
}
